console.time('总耗时')
const startTime = new Date().getTime()
const fs = require('fs')
const path = require('path')
const webp = require('webp-converter')
const chalk = require('chalk')
const sourceList = fs.readdirSync(path.join(__dirname, 'source'))
const outputPath = path.join(__dirname, 'output')
const isOutputPathExists = fs.existsSync(outputPath)
if (!isOutputPathExists) {
  fs.mkdirSync(path.join(__dirname, 'output'), { recursive: true }, (err) => {
    if (err) throw new Error(err)
  })
}

const webpToPng = (imgPath, i) => {
  return new Promise((resolve, reject) => {
    webp
      .cwebp(imgPath, path.join(outputPath, `${i.toString()}.png`), '-q 100')
      .then(() => {
        resolve('success')
      })
      .catch((err) => {
        reject(err)
      })
  })
}
const wrtieFile = (dataBuffer, i) => {
  return new Promise((resolve, reject) => {
    fs.writeFile(
      path.join(outputPath, `${i.toString()}.png`),
      dataBuffer,
      function (err) {
        if (err) {
          reject(err)
        } else {
          resolve('success')
        }
      }
    )
  })
}
const recursive = async (i) => {
  console.time(chalk.yellow(`图片${i.toString()}耗时`))
  let res = ''
  if (i < sourceList.length) {
    const p = path.join(__dirname, 'source', sourceList[i])
    const imageData = fs.readFileSync(p)
    const fileExtname = path.extname(p)
    if (fileExtname === '.webp') {
      // webp转png
      res = await webpToPng(p, i).catch((err) => {
        console.log(`图片${p}写入失败，错误信息：`, err)
      })
    } else {
      const imageBase64 = imageData.toString('base64')
      const dataBuffer = Buffer.from(imageBase64, 'base64')
      res = await wrtieFile(dataBuffer, i).catch((err) => {
        console.log(chalk.red(err))
      })
    }
    if (res && res === 'success') {
      console.log(
        '写入图片',
        chalk.green(i + '.png'),
        '成功。图片源：',
        chalk.yellowBright(p)
      )
      console.timeEnd(chalk.yellow(`图片${i.toString()}耗时`));
    }
    return recursive(i + 1)
  } else {
    const endTime = new Date().getTime()
    const finishTime = ((endTime - startTime) / 1000).toFixed(2)
    console.log(
      chalk.yellow('全部写入完毕！总耗时为：'),
      chalk.yellow(finishTime),
      '秒'
    )
    console.timeEnd('总耗时')
  }
}
recursive(0)
